package com.henry.db.migrate.task;

import com.henry.db.migrate.factory.DbFactory;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSetMetaData;

public class BaseTable {
    public static final int pageSize = 10000;
    private String targetTable;
    private String srcTable;
    private String srcCountSql;
    private String srcSelectSql;
    private String targetSql;
    private String[] colnames;
    public BaseTable(String targetTable) {
        this(targetTable, targetTable);
    }

    public BaseTable(String targetTable, String srcTable) {
        this.targetTable = targetTable;
        this.srcTable = srcTable;
        this.srcCountSql = "select count(1) from " + srcTable;
        this.srcSelectSql = "select * from " + srcTable;
        this.targetSql = "select * from " + targetTable;
    }

    public String[] getColnames(){
        if (this.colnames == null || this.colnames.length == 0) {
            Connection connection = DbFactory.getConnection("target");
            try {
                PreparedStatement preparedStatement = connection.prepareStatement(targetSql);
                ResultSetMetaData metaData = preparedStatement.getMetaData();
                int size = metaData.getColumnCount();
                String[] colnames = new String[size];
                String[] colTypes = new String[size];
                int[] colSizes = new int[size];
                for (int i = 0; i < size; i++) {
                    colnames[i] = metaData.getColumnName(i + 1);
                    colTypes[i] = metaData.getColumnClassName(i + 1);
                    colSizes[i] = metaData.getColumnDisplaySize(i + 1);
                }
                this.colnames = colnames;
            } catch (Exception e) {
                throw new RuntimeException("获取数据库"+targetTable+"表结构失败");
            }finally {
                DbFactory.close(connection);
            }

        }
        return this.colnames;
    }

    public String getSrcSelectSql() {
        return srcSelectSql;
    }

    public String getSrcCountSql() {
        return srcCountSql;
    }

    public String getTargetTable() {
        return targetTable;
    }

}
